package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleReplyMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.ArticleReply;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: wenjingyuan
 * @Date: 2023/09/27/20:45
 * @Description:
 */
@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private IArticleService articleService;
    @Override
    public void create(ArticleReply articleReply) {
        //非空校验
        if(articleReply==null || articleReply.getArticleId()==null
                ||articleReply.getPostUserId()==null
                || StringUtils.isEmpty(articleReply.getContent())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //设置默认值
        articleReply.setDeleteState((byte) 0);
        articleReply.setState((byte) 0);
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        Date date=new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        articleReply.setLikeCount(0);

        int row = articleReplyMapper.insertSelective(articleReply);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        //更新文章表的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("帖子回复成功 article id:"+articleReply.getArticleId()+"user id:"+articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if(articleId==null || articleId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);
        return result;
    }
}
